package com.sky.controller.admin.common;

import com.sky.result.Result;
import com.sky.utils.LocalServerUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@RestController
@Api("文件管理")
@Slf4j
@RequestMapping("/admin/common")

public class FileController {
    @Autowired
    private LocalServerUtil localServerUtil;
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    Result upload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extension = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + extension;
        File targetFile = new File(localServerUtil.getFolder() + fileName);
        try (
                InputStream inputStream = file.getInputStream();
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        ) {
            int size;
            byte[] buf = new byte[1024];
            while ((size = bufferedInputStream.read(buf)) != -1) {
                bufferedOutputStream.write(buf, 0, size);
            }
            bufferedOutputStream.flush();
        } catch (IOException ex) {
            log.error("File IO Exception!", ex);
        }
        String path = localServerUtil.getFilePath(fileName);
        return Result.success(path);
    }
}
